package com.thjk.bdf.preloan.service.ext.unitygateway.service;

import com.thjk.bdf.common.utils.DateUtils;
import com.thjk.bdf.common.utils.UidGenerator;
import com.thjk.bdf.preloan.service.config.AppConfig;
import com.thjk.bdf.preloan.service.config.LoanConfig;
import com.thjk.bdf.preloan.service.ext.common.ExtServiceException;
import com.thjk.bdf.preloan.service.ext.unitygateway.api.InvoiceData;
import com.thjk.bdf.preloan.service.ext.unitygateway.api.UnityGatewayResp;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class InvoiceDataQueryExtService {

    private static final Logger logger = LoggerFactory.getLogger(InvoiceDataQueryExtService.class);

    // 数仓url地址
    @Value("${SJ0001.url}")
    private String shucangQueryUrl;

    @Value("${netLoan.syscode}")
    private String orgCode; //机构码

    @Autowired
    private AppConfig appConfig;
    
    @Autowired
    private LoanConfig loanConfig;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取企业发票数据
     *
     * @param creditCode
     * @return
     */
    public InvoiceData queryInvoiceData(String creditCode) throws ExtServiceException {
        Map<String, Object> params = new HashMap<>();
        params.put("seriNo", UidGenerator.generateId(appConfig.getAppIp()));
        params.put("tranDate", DateUtils.formatDate(new Date(), "yyyyMMddHHmmss"));
        params.put("orgCode", orgCode);
        params.put("mchtTaxCd", creditCode);
        params.put("productCode", loanConfig.getProductCode());

        logger.info("调用数仓接口获取发票信息, request:{}", params);
        InvoiceDataResp invoceDataResp = restTemplate.postForObject(
                shucangQueryUrl , params, InvoiceDataResp.class);
        logger.info("调用数仓接口获取发票信息, request:{}, resp:{}", params, invoceDataResp);

        if (null == invoceDataResp) {
            logger.info("调用数仓接口获取发票信息返回结果为空, creditCode:{}", creditCode);
            throw new ExtServiceException("调用数仓接口获取发票信息返回结果为空");
        }
        if (!"0000".equals(invoceDataResp.getCode())) {
            logger.info("调用数仓接口获取发票信息返回结果异常, creditCode:{}", creditCode);
            throw new ExtServiceException("调用数仓接口获取发票信息返回结果异常");
        }

        return invoceDataResp.getData();

    }

    static class InvoiceDataResp extends UnityGatewayResp<InvoiceData> {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

    }

}
